import { LockOutlined, UserOutlined } from "@ant-design/icons";
import { Button, Form, Input, InputNumber, message, Spin, Steps } from "antd";
import React, { useEffect, useRef, useState } from "react";
import {
  ProFormText,
  LoginForm,
  PageContainer,
} from "@ant-design/pro-components";
import { history } from "umi";

import { PROJECT_NAME, TOKEN } from "@/constants";
import { getItem } from "@/utils/localstorage";
import styles from "../style.less";
import {
  mobileReg,
  mobileRegMessage,
  passWordReg,
  passWordRegMessage,
} from "@/utils/regExp";
import Https from "@/utils/Https";
import Https2 from "@/utils/Https2";
import logoPng from "@/assets/imgs/logo.png";
import { join } from "lodash";
message.config({
  maxCount: 1,
});

const Find: React.FC = (props) => {
  const { setType } = props;
  const [codeObj, setCodeObj] = useState({});
  const [newPhone, setNewPhone] = useState("");
  const [code, setCode] = useState("");
  const formRef = useRef();
  //验证码
  const [smsCode, setSmsCode] = useState("");
  const [btnStatus, setBtnStatus] = useState(false);
  const [count, setCount] = useState(60);
  const [findType, setFindType] = useState("1");
  const [oldParams, setOldParams] = useState({});
  const [loading, setLoading] = useState(false);
  // if (getItem(TOKEN)) {
  //   history.replace("/home");
  // }
  const getImg = async () => {
    const res = await Https2.get("/auth/code", {}, true);
    if (res.code == 200) {
      setCodeObj(res.data);
    }
  };
  //获取验证码
  const sendSms = async () => {
    const result = await Https.get(
      "/auth/sms/v2/code",
      { phonenumber: newPhone, uuid: codeObj.uuid, code: code },
      true
    );
    if (result.code === 200) {
      message.success("已发送验证码");
      setBtnStatus(true);
      let newCount = count;
      let timer = setInterval(() => {
        if (newCount > 0) {
          setCount(newCount--);
        } else {
          setCount(60);
          setBtnStatus(false);
          clearInterval(timer);
        }
      }, 1000);
    } else {
      message.error(result.msg || "发送失败，请稍后再试！");
    }
  };
  useEffect(() => {
    getImg();
  }, []);
  const handleSubmit = async (values: API.LoginParams) => {
    if (values.repeatPassword != values.password) {
      message.error("确认密码与密码不一致");
      return;
    }
    try {
      const res = await Https.post("/auth/restpw", values, true);
      if (res.code == 200) {
        message.success("重置密码成功");
        setType("login");
      } else {
        message.error(res.msg);
      }
    } catch (error) {
      console.log(error);
      message.error("重制密码失败，请重试！");
    }
  };
  const save = async () => {
    let result = await formRef?.current?.validateFields();
    if (findType == "1") {
      setOldParams(result);
      setLoading(true);
      let res = await Https.get("/auth/resetCheckSmsCode", result, true);
      setLoading(false);
      if (res.code == 200) {
        setFindType("2");
      } else {
        message.error(res.msg);
      }
    } else {
      if (result.repeatPassword != result.password) {
        message.error("确认密码与密码不一致");
        return;
      }
      let params = {
        username: oldParams.username,
        password: result.password,
      };
      setLoading(true);
      let res = await Https.post("/auth/restpw", params, true);
      setLoading(false);
      if (res.code == 200) {
        message.success("修改成功,请重新登录");
        setTimeout(() => {
          history.push("/user/login");
        }, 1000);
      } else {
        message.error(res.msg);
      }
    }
  };
  return (
    <Spin spinning={loading}>
      <div className={styles.FindBox}>
        <div className={styles.lefgBg}>
          <div className={styles.leftHeader}>
            <img src={logoPng} alt="" />
            <span>{PROJECT_NAME}</span>
          </div>
          <div className={styles.leftSteps}>
            <Steps
              direction="vertical"
              current={Number(findType) - 1}
              items={[
                {
                  title: "验证手机号",
                },
                {
                  title: "修改密码",
                },
              ]}
            />
          </div>
        </div>
        <div style={{ padding: "0 80px", width: "100%" }}>
          <div className={[styles.content, styles.findContent].join(" ")}>
            <LoginForm
              style={{ position: "relative" }}
              initialValues={{
                autoLogin: true,
              }}
              formRef={formRef}
              submitter={false}
            >
              <div
                className={styles.loginTitle}
                style={{ marginBottom: "8px" }}
              >
                忘记密码<span>(Forget Passwor)</span>
              </div>
              <div className={styles.loginTitleTips}>
                {findType == "1" ? "验证手机号" : "修改密码"}
              </div>
              {findType == "1" && (
                <>
                  <ProFormText
                    name="username"
                    fieldProps={{
                      prefix: <UserOutlined className={styles.prefixIcon} />,
                      maxLength: 20,
                    }}
                    placeholder="请输入手机号"
                    onChange={(e) => {
                      setNewPhone(e.target.value);
                    }}
                    rules={[
                      {
                        required: true,
                        message: "请输入手机号!",
                      },
                      { pattern: mobileReg, message: mobileRegMessage },
                    ]}
                  />
                  <div className={styles.codeWrapper}>
                    <ProFormText
                      noStyle
                      name="code"
                      placeholder="请输入图片验证码"
                      fieldProps={{
                        maxLength: 4,
                      }}
                      onChange={(e) => {
                        setCode(e.target.value);
                      }}
                    />
                    <img
                      onClick={() => getImg()}
                      className={styles.codePic}
                      src={
                        codeObj.img
                          ? `data:image/png;base64,${codeObj?.img}`
                          : {}
                      }
                    />
                  </div>
                  <Form.Item
                    className={styles.smsCodeBox}
                    label=""
                    required={true}
                  >
                    <Form.Item
                      name="smsCode"
                      rules={[
                        {
                          required: true,
                          message: "请输入短信验证码！",
                        },
                      ]}
                      noStyle
                    >
                      <Input
                        placeholder="请输入验证码"
                        maxLength={4}
                        onChange={(e) => {
                          setSmsCode(e.target.value);
                        }}
                      />
                    </Form.Item>
                    <Button
                      style={{
                        marginLeft: "10px",
                        height: "40px",
                        width: "130px",
                      }}
                      disabled={
                        newPhone.length != 11 || code.length != 4 || btnStatus
                      }
                      onClick={() => {
                        sendSms();
                      }}
                    >
                      {!btnStatus ? "获取短信验证码" : count + "s"}
                    </Button>
                  </Form.Item>
                </>
              )}
              {findType == "2" && (
                <>
                  <ProFormText.Password
                    name="password"
                    fieldProps={{
                      size: "large",
                      prefix: <LockOutlined className={styles.prefixIcon} />,
                      maxLength: 20,
                    }}
                    placeholder="请输入新密码"
                    rules={[
                      {
                        required: true,
                        message: "请输入新密码",
                      },
                    ]}
                  />
                  <ProFormText.Password
                    name="repeatPassword"
                    fieldProps={{
                      size: "large",
                      prefix: <LockOutlined className={styles.prefixIcon} />,
                      maxLength: 20,
                    }}
                    placeholder="确认密码"
                    rules={[
                      {
                        required: true,
                        message: "确认密码不能为空",
                      },
                      { pattern: passWordReg, message: passWordRegMessage },
                    ]}
                  />
                </>
              )}

              <div
                style={{
                  marginBottom: 24,
                  display: "flex",
                  justifyContent: "flex-end",
                }}
              >
                <Button
                  onClick={() => {
                    save();
                  }}
                  style={{ width: "100%" }}
                  type="primary"
                >
                  {findType == "1" ? "验证" : "修改密码"}
                </Button>
              </div>
              <div
                style={{
                  marginBottom: 24,
                  display: "flex",
                  justifyContent: "flex-end",
                }}
              >
                <a
                  onClick={() => {
                    history.push("/user/login");
                  }}
                >
                  返回登录{">>"}
                </a>
              </div>
            </LoginForm>
          </div>
        </div>
      </div>
    </Spin>
  );
};

export default Find;
